package uc.contancts;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import cn.onekit.CONFIG;
import cn.onekit.JSON;

/**
 * 获取联系人
 * 
 * @author Administrator
 *
 */
public class ContanctsInfo {
	private static ArrayList<Contanct> list;
	// 查询id
	public static ArrayList<Contanct> readContacts(Context context) {
		Uri rawContacsUri = Uri.parse("content://com.android.contacts/raw_contacts");
		list = new ArrayList<Contanct>();
		Cursor rawContacsCursor = context.getContentResolver().query(rawContacsUri, new String[] { "contact_id" }, null,
				null, null);
		if (rawContacsCursor != null) {
			while (rawContacsCursor.moveToNext()) {

				Contanct contancts = new Contanct();

				String contactId = rawContacsCursor.getString(rawContacsCursor.getColumnIndex("contact_id"));
				contancts.setId(contactId);
				// 根据id从date表中查询出对应的电话号码和联系人
				Uri dataUri = Uri.parse("content://com.android.contacts/data");
				Cursor dataCursor = context.getContentResolver().query(dataUri, new String[] { "data1", "mimetype" },
						"contact_id=?", new String[] { contactId }, null);
				if (dataCursor != null) {
					while (dataCursor.moveToNext()) {
						String data1 = dataCursor.getString(dataCursor.getColumnIndex("data1"));
						String mimetype = dataCursor.getString(dataCursor.getColumnIndex("mimetype"));
						if ("vnd.android.cursor.item/phone_v2".equals(mimetype)) {
							contancts.setNumber(data1);
						} else if ("vnd.android.cursor.item/name".equals(mimetype)) {
							contancts.setName(data1);
						}

					}
					list.add(contancts);
					dataCursor.close();
				}
			}
			rawContacsCursor.close();
		}
		fillAndSortData(list);

		return list;
	}

	public static ArrayList<String> getContanctsIds(Context context) {
		JSONArray contactsIdArray = null;
		ArrayList<String> listContanctId = new ArrayList<String>();
		Object temp = CONFIG.get(context, "systemwidgets");
		if (temp != null) {
			JSONObject systemwidgets = JSON.parse(temp);
			contactsIdArray = systemwidgets.optJSONArray("contacts");

		} else {
			CONFIG.set("systemwidgets", new JSONArray());
		}
		for (int i = 0; i < contactsIdArray.length(); i++) {
			try {
				String contactsId = contactsIdArray.get(i).toString();
				listContanctId.add(contactsId);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return listContanctId;

	}

	/*
	 * 进行排序
	 */
	private static void fillAndSortData(List<Contanct> list) {

		Collections.sort(list, new Comparator<Contanct>() {

			@Override
			public int compare(Contanct lhs, Contanct rhs) {
				int compareTo = lhs.getPinyin().compareTo(rhs.getPinyin());
				if (compareTo == 0) {
					return lhs.getId().compareTo(rhs.getId());
				}
				return compareTo;
			}
		});
	}
}
